const express = require("express");
const cores = require("cors");
const bodyParser = require("body-parser");

const app = express();
app.use(cores());

const multer = require("multer");
const crypto = require("crypto");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (file.fieldname === "image") {
      cb(null, "./uploads/image");
    } else {
      cb(null, "./uploads");
    }
  },
  filename: function (req, file, cb) {
    const md5name = crypto.createHash("md5").update(file.originalname).digest("hex");
    const fileExt = file.originalname.split(".").pop();
    const filename = md5name + "." + fileExt;
    cb(null, file.fieldname + "_" + filename);
  },
});

const upload = multer({ storage: storage });
app.use(upload.any());
app.use("/uploads", express.static("uploads"));

// extended is false the value can be a string or array , or any type (when extended is true).
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
  res.cc = (err, code = 1) => {
    res.send({
      code,
      msg: err instanceof Error ? err.message : err,
    });
  };
  next();
});

const jwtConfig = require("./jwt_config/index");
const { expressjwt: jwt } = require("express-jwt");
const { basePath, port } = require("./config");
// app.use(
//   jwt({
//     secret: jwtConfig.jwtSecretKey,
//     algorithms: ["HS256"],
//   }).unless({
//     path: [/^\/api\//],
//   })
// );

const loginRouter = require("./router/login");
const uploadRouter = require("./router/upload");
const userRouter = require("./router/user");

app.use("/api", loginRouter);
app.use("/upload", uploadRouter);
app.use("/user", userRouter);

const Joi = require("joi");
// this must after all router
app.use((err, req, res, next) => {
  if (err instanceof Joi.ValidationError) {
    res.send({
      code: 1,
      msg: err.message,
    });
  }
});

app.listen(port, () => {
  console.log(basePath);
});
